<?php
namespace app\admin;
use app\admin\model\setting\Setting as SettingModel;
use think\facade\Filesystem;
use think\Request;
use think\facade\Cache;
use SMS\SMS;
use Excel\Excel;
use think\facade\Session;
use think\facade\Cookie;
use think\facade\Request as RequestFacade;
use think\facade\View;
use app\admin\model\log\Log as logModel;
use app\admin\model\Image as ImageModel;
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
class common{
	public $error="";
	public $code="";
    
    public function getUserData($field){
    	global $_admin;
    	return $_admin[$field];
    }
    
    
    
	public static function excelTime($date, $time = false) {
	    if(function_exists('GregorianToJD')){
	        if (is_numeric( $date )) {
	        $jd = GregorianToJD( 1, 1, 1970 );
	        $gregorian = JDToGregorian( $jd + intval ( $date ) - 25569 );
	        $date = explode( '/', $gregorian );
	        $date_str = str_pad( $date [2], 4, '0', STR_PAD_LEFT )
	        ."-". str_pad( $date [0], 2, '0', STR_PAD_LEFT )
	        ."-". str_pad( $date [1], 2, '0', STR_PAD_LEFT )
	        . ($time ? " 00:00:00" : '');
	        return $date_str;
	        }
	    }else{
      		$date=$date>25568?$date+1:25569;
        	/*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/
        	$ofs=(70 * 365 + 17+2) * 86400;
        	$date = date("Y-m-d",($date * 86400) - $ofs).($time ? " 00:00:00" : '');
    	}
  		return $date;
	}
	
	//根据地区获取经纬度
	public static function gaode_get_lat($addr){
		global $_W,$_GPC;
		$key='fb1d809bfd398e14f79b260d90c722d6';
		$url="http://restapi.amap.com/v3/geocode/geo?&address=".$addr."&key=".$key."&output=json";
		$obj=json_decode(file_get_contents($url));
		if(isset($obj->status) && $obj->status==1){
			return $obj->geocodes[0]->location;
		}else{
			return false; 
		}
	}
	
	public function kuaidi($typeCom,$typeNu){
		global $_W,$_GPC;
	//	$typeCom = $_GPC["com"];//快递公司
	//	$typeNu = $_GPC["nu"];  //快递单号

		$AppKey='2c87d43b9b0d4579';//请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
		$url ='http://api.kuaidi100.com/api?id='.$AppKey.'&com='.$typeCom.'&nu='.$typeNu.'&show=2&muti=1&order=asc';
		
		//请勿删除变量$powered 的信息，否者本站将不再为你提供快递接口服务。
		$powered = '查询数据由：<a href="http://kuaidi100.com" target="_blank">KuaiDi100.Com （快递100）</a> 网站提供 ';
		
		
		//优先使用curl模式发送数据
		if (function_exists('curl_init') == 1){
		
		  $curl = curl_init();
		  curl_setopt ($curl, CURLOPT_URL, $url);
		  curl_setopt ($curl, CURLOPT_HEADER,0);
		  curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
		  curl_setopt ($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
		  curl_setopt ($curl, CURLOPT_TIMEOUT,5);
		  $get_content = curl_exec($curl);
		  curl_close ($curl);
		}else{
		  include("snoopy.php");
		  $snoopy = new snoopy();
		  $snoopy->referer = 'http://www.google.com/';//伪装来源
		  $snoopy->fetch($url);
		  $get_content = $snoopy->results;
		}
		return $get_content;
	}


    /**
     * 实例化execl操作类
     * @param $filename string 路径
     * @param $show_key bool 是否显示key
     * @param $firstRowTitle int 数据开始行数
     * @return array|string
     */
	 public static function importData($filename,$show_key,$firstRowTitle=2){
	 	$execlObj=new Excel();
	 	$data=$execlObj->import($filename,$show_key,$firstRowTitle);
	 	return $data;
	 }
	 
	 /**
	  * 
	  * 导出
	  */
	public function exportFile($file,$datas,$headername){
		if(empty($datas)){
			return false;
		}
		$execlObj=new Excel();
		$data=[];
		if($datas){
			foreach($datas as $k=>$v){
				foreach($v as $key=>$val){
					if(is_numeric($val) && strlen($val)>5){
						$data[$k][$key]="\t".$val."\t";
					}else{
						$data[$k][$key]=$val;
					}
				}
				unset($datas[$k]);
			}
		}

		$execlObj->exportExcel($file,$data,$headername);
		exit;
	}
	 /**
	  * 处理图片
	  */
	 public static function getImportDataFile(){
	 	$files = request()->file('file');
		$file_name=$files->getOriginalName();
		$savename = Filesystem::disk('public')->putFile( 'file', $files);
        //获取文件路径
        $url_path=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$savename;
        $path= $_SERVER['DOCUMENT_ROOT'].'/storage'.'/'.$savename;
        $arr=[
            'url'=>$url_path,
            'path'=>$path,
        ];
        return $arr;
	 }
	 
	/**
     * 处理图片
     * @param disk string filesystem配置项
     * @file_path string 文件路径
     * @param is_add 0不添加缩略图1添加
     */
    public static function getImportDataFileNew($disk, $file_path,$file_name='',$_is_add=0)
    {
    	if(isset($file_name) && !empty($file_name)){
    		$files = request()->file($file_name);
    	}else{
       		$files = request()->file('file');
        }
        $file_name = $files->getOriginalName();
        if (empty($file_path)) {
            $disk = "public";
        }
        $savename = \think\facade\Filesystem::disk($disk)->putFile($file_path, $files);
       
        $path = substr(__FILE__,0,stripos(__FILE__,'app'))."/public/storage/".$savename;
        
        //获取文件路径
        $path_file = $_SERVER['REQUEST_SCHEME']."://". $_SERVER['HTTP_HOST'] .DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . $savename;
        if($_is_add==1){
        	$_thum_path=common::getThumImage($path,$savename);
        	common::insertImage($path_file,$_thum_path);
        }
        //存储到数据库中
        return ['path'=>$path,'name'=>common::getPathName($path)];
    }
    public static function getPathName($_path_file){
    	$_new_data=explode(DIRECTORY_SEPARATOR,$_path_file);
        return end($_new_data);
    }
    
    //根据原文件拿取缩略图
    public static function getThumUrl($_url){
    	return $_url;
    	if(is_array($_url)){//数组
    		$_new_data=[];
    		foreach($_url as $k=>$v){
    			$_new_data[]=common::getThumUrlData($v);
    		}
    		return $_new_data;
    	}else{//单独的
    		return common::getThumUrlData($_url);
    	}
    }
    public static function getThumUrlData($_url){
    	//1.处理数据
    	$_array_data=explode(DIRECTORY_SEPARATOR,$_url);
    	
    	//2.拼接数据
    	$_file_name=end($_array_data);
    	
    	//3.获取缩略图的Url
    	$_thum_file=str_replace($_file_name,'thum_'.$_file_name,$_url);
    	//4.判断当前缩略图是否存在
    	$_new_url=substr(__FILE__,0,stripos(__FILE__,'app')).'public/'.substr($_thum_file,stripos($_thum_file,'storage'));
    	$_www_url=substr(__FILE__,0,stripos(__FILE__,'app')).'public/'.substr($_url,stripos($_url,'storage'));
    	if(file_exists($_new_url)){
    		return $_thum_file;
    	}
    	//5.不存在重新生成
    	$savename=substr($_url,stripos($_url,'storage')+7);
    	$_thum_path=common::getThumImage($_www_url,$savename);
    	//6.保存到数据库
    	common::insertImage($_url,$_thum_path);
    	return $_thum_path;
    }
    /**
     * @title 获取缩略图
     */
    public static function getThumImage($path,$savename){
    	$image = \think\Image::open($path);
        $_new_data=explode(DIRECTORY_SEPARATOR,$path);
        $_file_name=end($_new_data);
        $_thum_file=str_replace($_file_name,'thum_'.$_file_name,$path);
        //拿取基本配置文件 
        $image->thumb(config('key.width'),config('key.height'))->save($_thum_file);
        $_thum_path=$_SERVER['REQUEST_SCHEME']."://". $_SERVER['HTTP_HOST'].DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$savename;
        $_thum_path=str_replace($_file_name,'thum_'.$_file_name,$_thum_path);
        return $_thum_path;
    }
    
    public static function insertImage($_path,$_thum_image){
    	$_image_obj=new ImageModel();
    	$_data=[
    		'image_md5'=>md5($_path),
    		'url'=>$_thum_image,
    		'create_time'=>time()
    	];
    	$_image_obj->insertImageThum($_data);
    }
	 /**
     * 生成token
     * @param  string $str      加密的字符串
     * @param  [type] $auth_key 加密符
     * @return string           加密后长度为32的字符串
     */
    public static function token($str, $auth_key = '')
    {
        return '' === $str ? '' : md5(sha1($str) . $auth_key);
    }
	/**
	 * 获取TOKEN并处理TOKEN格式
	 * 
	 */
	public function getToken(){
		$Request=new Request();
		
		if(config("status.isphp")==1){
    		$data=Session::all();
    		if(!isset($data['data']) && !$data['data']=Cookie::get('data')){
    			$this->error="请先登陆";
    			$this->code="202";
    			return false;
    		}else{
    			Session::set("data",$data['data']);
    			$cookie_data=json_decode($data['data'],true);
    			Session::set("user_id",$cookie_data['id']);
				Session::set("roles_id",$cookie_data['roles_id']);
				Session::set("username",$cookie_data['username']);
				Session::set("job_id",$cookie_data['job_id']);
				Session::set("department_id",$cookie_data['department_id']);
    		}
    		$json_data=json_decode($data['data'],true);
    		$token=$json_data['token'];
		}else{
			if(empty($Request->header())){
				$token=isset($_SERVER['HTTP_TOKEN'])?$_SERVER['HTTP_TOKEN']:'';
			}else{
				$token=$Request->header('HTTP_TOKEN')?$Request->header('HTTP_TOKEN'):false;
			}
		}
		
		if(!$token){
			$this->error=config('adminMessage.token.tokenCheckError.msg');
    		$this->code=config('adminMessage.token.tokenCheckError.code');
    		return false;
		}
		//2.拿取用户的ID
		$requestTokenData=explode('|',base64_decode($token));
		return $requestTokenData;
	}
	
	public function tokenMd5($token,$id,$time){
		$token=md5(md5($token.$id).$id.$time);
		return $token;
	}
	
	//获取用户是总管理员还是普通管理员 管理员可以查询全部，普通管理员管理角色为他自己的下级
	public function checkRole(){
		$common=new common();
    	$operation=$common->getOperation();
    	$roles=$operation['roles_id'];
    	//如果该角色不等于最初管理员 则返回0 等于管理员则为1
    	if(stripos($roles,'1')!==0 && stripos($roles,'1')==false){
    		return 0;
    	}
    	return 1;
	}
	/**
	 * 获取操作用户
	 * 
	 */
	public function getOperation(){
    	$admin_obj=new \app\admin\model\index\Admin;
		$headerToken=$this->getToken();
		$id=$headerToken[1];
		$token=$headerToken[0];
		if(!$token){
			$this->error=config('message.token.tokenError');
			return false;
		}
    	$where=[
    		'id'=>$id
    	];
    	$operation=$admin_obj->getAdmin($where);
    	return $operation;
    }
	/**
	 * 存储该手机每天的发信发送量
	 * 
	 */
	public static function addCodeSendNumber($mobile){
    	$number=Cache::get($mobile);
    	if(!$number){
    		$number=1;
    	}else{
    		$number++;
    	}
    	Cache::set($mobile,$number);
    	
    }
	//加载第三方的验证码
	public static function send_message($param){
		$smsObj=new SMS();
		$setting=common::getSmsSetting();
		$r=$smsObj->send($setting,$param);
		if($r==false){
			$data['error']=$smsObj->error;
			$data['code']=$smsObj->code;
			$data['result']=0;
		}else{
			$data['success']=$smsObj->success;
			$data['code']=$smsObj->code;
			$data['result']=1;
		}
		return $data;
	}
	
	//获取验证码的基本设置
	public static function getSmsSetting(){
		$sms=new \app\api\model\sms\Sms;
		$sms_setting=$sms->getSetting(['type'=>0]);
		return $sms_setting;
	}
	
	//验证码生成器
	public static function get_code($mobile){
		$code=mt_rand(111111, 999999);
		$msg="你的验证码是:".$code;
		if($mobile && $code){
			Cache::set($mobile."code_time",time(),100);//设置过期时间
			Cache::set($mobile.'mobile', $mobile,100);
			Cache::set($mobile.'code', $code,100);
		}
		$smsTemplate=new \app\api\model\sms\SmsTemplate;
		$smsTemplateData=$smsTemplate->getSetting(['type'=>0]);
		$param=[
			'query'=>[
				 'RegionId' => "cn-hangzhou",
				 'PhoneNumbers' => $mobile,
				 'SignName' => $smsTemplateData['singName'],//config("sms.send_code.singName"),
				 'TemplateCode' =>$smsTemplateData['template_id'],//config("sms.send_code.template_id"),
				 'TemplateParam'=>json_encode([$smsTemplateData['variable']=>$code])
			]
		];
		$result=self::send_message($param);
		return $result;
	}
	
	/**
     * 菜单遍历
     * 
     */

    public static function formatList($menuList){
        $list = array();
        $tmp = array();  
        foreach ($menuList as $item) {
            $tmp[$item['id']] = $item;
        }
        foreach ($menuList as $item){
			/*if($item['pid']==0){
				continue;
			}*/
            if (isset($tmp[$item['pid']])){
                $tmp[$item['pid']]['child'][] = &$tmp[$item['id']];
            }
            else{
                $list[] = &$tmp[$item['id']];
            }
        }
        //排序
        foreach($list as $k=>$v){
        	
        }
        unset($tmp);

        return $list;
    }
    /**
     * @Purpose 处理城市成递规形式
     */
    public static function formatListForCity($menuList,$ids){
    	
    	foreach($menuList as $k=>$v){
    		if(in_array($v['region_code'],$ids)){
    			$menuList[$k]['checked']=true;
    		}else{
    			$menuList[$k]['checked']=false;
    		}
    		
    		$menuList[$k]['title']=$v['region_name'];
    		$menuList[$k]['child']=[];
    	}
    	$list = array();
        $tmp = array();  
        foreach ($menuList as $item) {
            $tmp[$item['region_id']] = $item;
            //如果当前下级是选中的，那么默认上级是选中的
            if($item['checked']){
            //	$tmp[$item['pid']]['checked']=true;
            }
        }
     // var_dump($menuList,$tmp);exit;
        foreach ($menuList as $item){
            if (isset($tmp[$item['region_pid']])){
                $tmp[$item['region_pid']]['child'][] = &$tmp[$item['region_id']];
               // var_dump(222222222,$tmp);exit;
            }
            else{
                $list[] = &$tmp[$item['region_id']];
            }
        }
     
        //排序
        foreach($list as $k=>$v){
        	
        }
        unset($tmp);
        return $list;
    }
    /**
     * 
     */
    public static function formatListNew($menuList,$_job_list){
    	$_job_list_id=array_column($_job_list,'id');
    	foreach($menuList as $k=>$v){
    		if(isset($v['tag'])){
    			foreach($v['tag'] as $kk=>$vv){
    				if(in_array($vv['id'],$_job_list_id)){
		    			$menuList[$k]['tag'][$kk]['checked']=true;
		    		}else{
		    			$menuList[$k]['tag'][$kk]['checked']=false;
		    		}
    			}
    		}
    		if(in_array($v['id'],$_job_list_id)){
    			$menuList[$k]['checked']=true;
    		}else{
    			$menuList[$k]['checked']=false;
    		}
    		$menuList[$k]['title']=$v['menu_name'];
    		$menuList[$k]['child']=[];
    	}
    	$list = array();
        $tmp = array();  
        foreach ($menuList as $item) {
            $tmp[$item['id']] = $item;
        }
        foreach ($menuList as $item){
			if($item['status']==0){
				continue;
			}
            if (isset($tmp[$item['pid']])){
                $tmp[$item['pid']]['child'][] = &$tmp[$item['id']];
            }
            else{
                $list[] = &$tmp[$item['id']];
            }
        }
        //排序
        foreach($list as $k=>$v){
        	
        }
        unset($tmp);

        return $list;
    }
    
    //把菜单和菜单下面的标签进行组合
    public static function combination($menu,$tag){
    	foreach($menu as $k=>$v){
    		if(isset($v['function']) && !empty($v['function'])){
    			$menu[$k]['function']=trim($v['function']);
    		}
    		foreach($tag as $kk=>$vv){
    			if(isset($v['menu_permission'])){
    				if(stripos($v['menu_permission'],(string) $vv['id'])!==false){
    					$menu[$k]['tag'][]=$vv;
    				}
    			}else{
    				if($v['id']==$vv['pid']){
    					$menu[$k]['tag'][]=$vv;
    				}
    			}
    		}
    	}
    	return $menu;
    }
    //把管理员和用户的菜单进行组合
    public static function combination_menu($manager_menu,$user_menu){
    	foreach($manager_menu as $k=>$v){
    		foreach($user_menu as $kk=>$vv){
    			
    		}
    	}
    }
    
    /**
     * base64图片上传
     * 
     */
	public static function upload_image_bsae64_single($pic1,$files=""){
		$file=substr(__FILE__,0,stripos(__FILE__,'app'));
		if (!file_exists($file.'public'.DIRECTORY_SEPARATOR.date('Y-m-d'))) {
         	mkdir($file.'image'.DIRECTORY_SEPARATOR.'learning'.DIRECTORY_SEPARATOR.'test'.DIRECTORY_SEPARATOR.date('Y-m-d'), 0777, true);
        }
		
		file_put_contents($file.'images'.DIRECTORY_SEPARATOR.'learning'.DIRECTORY_SEPARATOR.'test'.DIRECTORY_SEPARATOR.date('Y-m-d').DIRECTORY_SEPARATOR.'a1.text', $pic1);
        $user_pic = substr(strstr($pic1, ','), 1);
		
        $imgs = base64_decode($user_pic);
        $uploadpath = $file.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'learning'.DIRECTORY_SEPARATOR.'formal'.DIRECTORY_SEPARATOR.date('Y-m-d').DIRECTORY_SEPARATOR;
        if (!file_exists($uploadpath)) {
         	$r=mkdir($uploadpath, 0777, true);
        }
        $pic_path = $uploadpath . time() . mt_rand(1000, 9999) . ".jpg";
        //保存base64图片
        file_put_contents($pic_path, $imgs);
		$pic=substr($pic_path,stripos($pic_path,DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR));
		$pic=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$pic;
		return $pic;
	}
	
	public static function jumpError($message="失败",$time=3,$uri=''){
		
		if(!isset($uri) || !$uri){
			$uri=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/admin/index.admin/show";
		}
		$time=$time?$time:3;
		$data=[
			'message'=>$message,
			'time'=>$time,
			'uri'=>$uri
		];
		View::assign("error",$data);
		return View::fetch('/common/error');
	}
	
	public static function jumpSuccess($message="成功",$time=3,$uri=''){
		if(!isset($uri) || !$uri){
			$uri=$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/admin/index.admin/show";
		}
		$time=$time?$time:3;
		$data=[
			'message'=>$message,
			'time'=>$time,
			'uri'=>$uri
		];
		
		View::assign("error",$data);
		return View::fetch('/common/success');
	}
	
	//统一返回函数
	public static function return_json_ajax($data,$msg,$code=0){
		if($data==false){
			$result=[
				'status'=>201,
				'message'=>$msg,
				'msg'=>$msg,
				'code'=>$code	
			];
		}else{
			if(isset($data['data'])){
				$result=[
					'status'=>200,
					'message'=>$msg,
					'msg'=>$msg,
					'data'=>$data['data'],
					'code'=>$code
				];
				if(isset($data['count'])){
					$result['count']=$data['count'];
				}
			}else{
				$result=[
					'status'=>200,
					'message'=>$msg,
					'msg'=>$msg,
					'data'=>$data,
					'code'=>$code
				];
			}
		}
		return json($result);
	}
	
	//统一返回函数
	public static function return_json($data,$msg,$code=0){
		if($data==false){
			$result=[
				'status'=>201,
				'message'=>$msg,
				'msg'=>$msg,
				'code'=>$code	
			];
		}else{
			if(isset($data['data'])){
				$result=[
					'status'=>200,
					'message'=>$msg,
					'data'=>$data['data'],
					'msg'=>$msg,
					'code'=>$code
				];
				if(isset($data['count'])){
					$result['count']=$data['count'];
				}
			}else{
				$result=[
					'status'=>200,
					'message'=>$msg,
					'msg'=>$msg,
					'data'=>$data,
					'code'=>$code
				];
			}
		}
		return json($result);
		
	}
	public static function return_json_layui($data,$msg,$code=0){
		if (is_array($data) && !$data) {
            $data = [];
        }
        if (is_bool($data) && !$data) {
            $data = false;
        }
        if(isset($data['data'])){
        	 $_result = array(
	            'code' => $code,
	            'msg' => $msg,
	            'data' => $data
	        );
        }else{
	        $_result = array(
	            'code' => $code,
	            'msg' => $msg,
	            'data' =>array('data'=>$data)
	        );
        }
         if(isset($data['count'])){
        	$_result['data']['data']=$data['data'];
        	$_result['data']['total']=$data['count'];
	      //  $_result['count']=$data['count'];
        }else{
        	if(isset($data['id'])){
        		$data['id']=(string) $data['id'];
        	}
        	$_result['data']['data']=$data;
        	$_result['data']['total']=0;
        }
        if(isset($data['or_data'])){
        	$_result['or_data']=$data['or_data'];
        }
        if(isset(Request()->param()['no_ajax']) && Request()->param()['no_ajax']==1){
        	
        	return $_result;
        }
        return json($_result);
	}
	//存储登陆日志
	public static function insertLog($function,$name,$text,$admin_id){
		$data=array(
			'addr_ip'=>RequestFacade::host(),
			'admin_id'=>$admin_id,
			'name'=>$name,
			'function'=>$function,
			'log'=>serialize($text),
			'create_time'=>time(),
			'type'=>0
		);
		$log=new \app\admin\model\log\Log;
		$log->insertLog($data);
	}
	
	public static function getLog($where,$flag=0,$field,$order){
		$log=new \app\admin\model\log\Log;
		if($flag==1){
			$data=$log->findLog($where,$field,$order);
		}else{
			$data=$log->selectLog($where);
		}
		return $data;
	}
	
		/**
	 * 获取订单号
	 */
	public static function getOrdersn($header,$lat){
		return $header.date('YmdHis').$lat;
	}
	
	public static function get($key,$datakey){
		$md5Key=md5($key);
		$md5DataKey=md5(json_encode($datakey));
		$result=Cache::get($md5Key);
		self::$md5Key=$md5Key;
		self::$result=$result;
		self::$dataKey=$md5DataKey;
		$data=[];
		if(isset($result[$md5DataKey])){
			$data=$result[$md5DataKey];
		}
		//$data=[];
		return ["md5Key"=>$md5Key,'dataKey'=>$md5DataKey,'result'=>$result,'data'=>$data];
	}
	
	public static $md5Key;
	public static $result;
	public static $dataKey;
	
	public static function set($data,$time=0){
		self::$result[self::$dataKey]=$data;
		if($time>0){
			Cache::set(self::$md5Key,self::$result,$time);
		}else{
			Cache::set(self::$md5Key,self::$result);
		}
		
	}
	
	public static function delete($key){
		Cache::delete(md5($key));
	}

	
}